package com.example.Arithmetic.Lettcode;

import org.junit.jupiter.api.Test;

/**
 * 日期：2024/1/2
 * 时间：11:39
 * 描述：求某个数的指定次幂
 */
public class E01Lettcode52 {
    public double myPow(double x, int n) {
        long N = n;
        if (N < 0) {
            return 1.0 / myPow1(x, (int) -N);
        }
        return myPow1(x, n);
    }

    public double myPow1(double x, int n) {
        if (n == 0) {
            return 1.0;
        }
        if (n == 1) {
            return x;
        }
        double v = myPow1(x, n / 2);
        if ((n & 1) == 0) {
//            偶数情况
            return v * v;
        } else {
//            奇数情况
            return v * v * x;
        }
    }

    @Test
    public void main() {
        E01Lettcode52 e01Lettcode52 = new E01Lettcode52();
        System.out.println(e01Lettcode52.myPow(2, -2));
    }
}

